/*
 * @Description:
 * @Author: Rfan
 * @Date: 2022-06-21 21:37:30
 * @LastEditTime: 2022-12-31 19:17:03
 */

import { useEffect, useState } from 'react';
import { Button, Progress, Space, Table, Tag, Typography } from 'antd';
import classNames from 'classnames/bind';
import { useFormatMessage } from '@/utils/intlHelpers';
import { useExportMgtRouterTypeContext } from '../contexts/ExportMgtRouterTypeContext';
import { useExportMgtContext } from '../contexts/ExportMgtContext';
import { byteConvert, formatDate, isNullObj } from '@/utils';
import { IPageQuery } from '@/interfaces/global';

import styles from '../styles/pageList.module.scss';
import { wsState } from '@/store/WSStore';
import { observer } from 'mobx-react-lite';
import { EnumExportStatus } from '@/view/management/ExportMgt/dictionaries';

const cx = classNames.bind(styles);

const { Column } = Table;

const PageList = (props: any) => {
  const { className } = props;
  const { type: businessType } = useExportMgtRouterTypeContext();

  const {
    exportList,
    selectExportType,
    selectItems,
    setSelectKey,
    getExportListFunc,
    startDetectTaskFunc,
    startPackageTaskFunc,
    startTransferTaskFunc,
    deleteExportFunc,
    setExportItemProcess,
    exportTypeFilter,
    stateFilter,
    stateColorFilter
  } = useExportMgtContext();
  const formatMessage = useFormatMessage();
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [listQuery, setListQuery] = useState<IPageQuery>({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });

  useEffect(() => {
    setListQuery({
      pageNo: 1,
      pageSize: 10,
      param: {
        businessType,
        exportType: selectExportType
      }
    });
  }, [selectExportType]);

  useEffect(() => {
    if (listQuery && !isNullObj(listQuery.param)) {
      setLoading(true);
      getExportListFunc(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  // 监听ws消息更改进度
  useEffect(() => {
    const { archiveExport } = wsState;
    console.log('ws', archiveExport);
    if (archiveExport) {
      setExportItemProcess(archiveExport);
    }
  }, [wsState.archiveExport]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  /**
   * @description: 根据传入的列表判断按钮是否展示
   * @param {number[]} allowList 允许展示的状态列表
   * @param {number} state 当前的状态
   * @return {boolean} 是否可以展示
   */
  const showBtnFunc = (allowList: number[], state: number): boolean => {
    return allowList.indexOf(state) >= 0;
  };

  /**
   * @description: 开始检测任务
   * @param {number} id 条目id
   */
  const startDetectTask = (id: number) => {
    startDetectTaskFunc(id);
  };

  /**
   * @description: 开始打包任务
   * @param {number} id 条目id
   */
  const startPackageTask = (id: number) => {
    startPackageTaskFunc(id);
  };

  /**
   * @description: 开始移交任务
   * @param {number} id 条目id
   */
  const startTransferTask = (id: number) => {
    startTransferTaskFunc(id);
  };

  return (
    <div className={className}>
      <Table
        dataSource={exportList}
        loading={loading}
        rowKey="id"
        scroll={{ x: 'max-content' }}
        rowSelection={rowSelection}
        bordered
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      >
        <Column title="序号" dataIndex="id" key="id" align="center" />
        <Column title="导出名称" dataIndex="name" key="name" />
        <Column
          title="导出类型"
          dataIndex="exportType"
          key="exportType"
          align="center"
          render={(text) => exportTypeFilter(text)}
        />
        <Column title="档案类型" dataIndex="archiveTypeName" key="archiveTypeName" align="center" />
        <Column
          title="创建时间"
          dataIndex="startTime"
          key="startTime"
          align="center"
          render={(text) => (text ? formatDate(text) : '')}
        />
        <Column
          title="完成时间"
          dataIndex="endTime"
          key="endTime"
          align="center"
          render={(text) => (text ? formatDate(text) : '')}
        />
        <Column
          title="导出大小"
          dataIndex={['exportInfo', 'size']}
          key="size"
          align="center"
          render={(size) => (size ? byteConvert(size) : size)}
        />
        <Column
          title="条目个数"
          dataIndex={['exportEntryInfo', 'entryIdList']}
          key="entryNum"
          align="center"
          render={(text) => text.length}
        />
        <Column
          title="状态"
          dataIndex="status"
          key="status"
          align="center"
          render={(status: number, record: any) => (
            <>
              {record.progress && <Progress percent={record.progress} steps={5} size="small" />}
              <Tag color={stateColorFilter(status)}>{stateFilter(status)}</Tag>
            </>
          )}
        />
        <Column
          title="导出文件"
          dataIndex="exportInfo"
          key="exportFile"
          render={({ name, url, deleted }, record: any) => (
            <Space>
              <Typography.Link href={url} disabled={deleted} target="_blank">
                {name}
              </Typography.Link>
              {/* 暂时屏蔽 */}
              {/* {url && ( */}
              {/*  <Button */}
              {/*    type="link" */}
              {/*    disabled={deleted} */}
              {/*    onClick={() => { */}
              {/*      deleteExportOriginFunc(record.id); */}
              {/*    }} */}
              {/*  > */}
              {/*    删除 */}
              {/*  </Button> */}
              {/* )} */}
            </Space>
          )}
        />
        <Column
          title={formatMessage('tableAction')}
          key="action"
          className={cx('action-col')}
          align="center"
          render={(_text, record: any) => (
            <Space>
              {showBtnFunc([EnumExportStatus.DetectPending], record.status) && (
                <Button
                  type="link"
                  size="small"
                  onClick={() => {
                    startDetectTask(record.id);
                  }}
                >
                  检测
                </Button>
              )}
              {/* {showBtnFunc([EnumExportStatus.PackagePending], record.status) &&  ( */}
              {/*  <Button */}
              {/*    type="link" */}
              {/*    size="small" */}
              {/*    onClick={() => { */}
              {/*      startPackageTask(record.id); */}
              {/*    }} */}
              {/*  > */}
              {/*    打包 */}
              {/*  </Button> */}
              {/* )} */}
              {showBtnFunc([EnumExportStatus.TransferPending], record.status) && (
                <Button
                  type="link"
                  size="small"
                  onClick={() => {
                    startTransferTask(record.id);
                  }}
                >
                  移交
                </Button>
              )}
              <Button
                type="link"
                size="small"
                danger
                onClick={() => {
                  deleteExportFunc(record.id);
                }}
              >
                删除
              </Button>
            </Space>
          )}
        />
        <Column title="报告" key="report" align="center" />
      </Table>
    </div>
  );
};

export default observer(PageList);
